package com.wing.device.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.GenerateNiceStringUtil;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.device.dao.MaintenanceDao;
import com.wing.device.model.entity.Maintenance;

import com.wing.device.model.entity.MaintenanceClaim;
import com.wing.device.model.response.MaintenanceVo;
import com.wing.product.model.entity.Product;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-08-19 16:12
 **/
@Service
@Slf4j
public class DeviceMaintenanceServiceImpl extends ServiceImpl<MaintenanceDao, Maintenance> implements DeviceMaintenanceService {

    @Resource
    private DeviceMaintenanceClaimService deviceMaintenanceClaimService;

    private static final String ALREADY = "2";

    /**
     * 设备维修保养任务列表
     *
     * @param pg  分页信息
     * @param map 过滤条件
     * @return
     */
    @Override
    public IPage<Maintenance> pageList4app(Page<Maintenance> pg, Map map) {
        List<Maintenance> list = baseMapper.list4app(pg, map);
        pg.setRecords(list);
        return pg;
    }

    /**
     * 根据id查询维保详情
     *
     * @param id
     * @return
     */
    @Override
    public MaintenanceVo getMaintenanceBy(Long id,String databaseUser) {
        return baseMapper.getMaintenanceBy(id, databaseUser);
    }

    /**
     * 认领任务
     *
     * @param type
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInfoBy(Maintenance type) {
        //生成认领从表信息
        MaintenanceClaim maintenanceClaim = new MaintenanceClaim();
        maintenanceClaim.setClaimNo(UniqueIdGeneratorUtil.generateUniqueId("RLWB", "yyyyMMdd", 1000, 9999));
        maintenanceClaim.setTaskId(type.getId());
        maintenanceClaim.setCreator(JwtUtils.getLoginUserId());
        maintenanceClaim.setCreatorName(JwtUtils.getLoginUsername());
        maintenanceClaim.setCreateTime(LocalDateTime.now());
        maintenanceClaim.setModifier(JwtUtils.getLoginUserId());
        maintenanceClaim.setUpdateTime(LocalDateTime.now());
        maintenanceClaim.setModifierName(JwtUtils.getLoginUsername());
        boolean save = this.deviceMaintenanceClaimService.save(maintenanceClaim);
        if (save) {
            type.setStatus(ALREADY);
            type.setClaimId(maintenanceClaim.getId());
            type.setClaimTime(LocalDateTime.now());
            //修改主表认领信息
            baseMapper.updateById(type);
        }
    }
}
